const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs-extra');

let mainWindow;
let welcomeWindow;

function createWelcomeWindow() {
  welcomeWindow = new BrowserWindow({
    width: 600,
    height: 500,
    resizable: false,
    frame: false,
    alwaysOnTop: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, 'assets', 'icon.ico'),
    title: 'ZeusGIS - 启动中...',
    show: false
  });

  welcomeWindow.loadFile('welcome.html');

  welcomeWindow.once('ready-to-show', () => {
    welcomeWindow.show();
    
    // 3秒后关闭欢迎窗口并打开主窗口
    setTimeout(() => {
      createMainWindow();
      welcomeWindow.close();
    }, 3000);
  });

  welcomeWindow.on('closed', () => {
    welcomeWindow = null;
  });
}

function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    icon: path.join(__dirname, 'assets', 'icon.ico'),
    title: 'ZeusGIS - 专业的GIS工具合集',
    show: false
  });

  mainWindow.loadFile('index.html');

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  // 开发模式下打开开发者工具
  if (process.argv.includes('--dev')) {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.whenReady().then(createWelcomeWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// IPC 处理程序
ipcMain.handle('select-file', async (event, options) => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [
      { name: 'Excel文件', extensions: ['xlsx', 'xls'] }
    ],
    ...options
  });
  
  return result;
});

ipcMain.handle('select-save-path', async (event, options) => {
  const result = await dialog.showSaveDialog(mainWindow, {
    filters: [
      { name: 'Excel文件', extensions: ['xlsx'] }
    ],
    ...options
  });
  
  return result;
});

ipcMain.handle('check-cache-exists', async (event, cacheKey) => {
  const cacheDir = path.join(__dirname, 'cache');
  const cacheFile = path.join(cacheDir, `${cacheKey}.json`);
  return await fs.pathExists(cacheFile);
});

ipcMain.handle('load-cache', async (event, cacheKey) => {
  const cacheDir = path.join(__dirname, 'cache');
  const cacheFile = path.join(cacheDir, `${cacheKey}.json`);
  
  try {
    const data = await fs.readJson(cacheFile);
    return data;
  } catch (error) {
    return null;
  }
});

ipcMain.handle('save-cache', async (event, cacheKey, data) => {
  const cacheDir = path.join(__dirname, 'cache');
  await fs.ensureDir(cacheDir);
  const cacheFile = path.join(cacheDir, `${cacheKey}.json`);
  
  try {
    await fs.writeJson(cacheFile, data);
    return true;
  } catch (error) {
    console.error('保存缓存失败:', error);
    return false;
  }
});

ipcMain.handle('clear-cache', async (event, cacheKey) => {
  const cacheDir = path.join(__dirname, 'cache');
  const cacheFile = path.join(cacheDir, `${cacheKey}.json`);
  
  try {
    await fs.remove(cacheFile);
    return true;
  } catch (error) {
    return false;
  }
});